import * as fs from 'fs'
import * as path from 'path'
import * as sinon from 'sinon'
import {expect} from 'chai'
import {hasFilesInDirectory} from '../src/util'

async function createSubdirectoryAndFile(dirPath: string, createDir: boolean, createFile: boolean): Promise<void> {
    const subDirName = `new-subdirectory.${Date.now()}`
    const subDirPath = path.join(dirPath, subDirName)

    const fileName = `new-file.${Date.now()}`
    const filePath = path.join(subDirPath, fileName)

    try {
        // 创建 dir 基础目录
        await fs.promises.mkdir(dirPath, {recursive: true})

        // 创建子目录
        if (createDir) {
            await fs.promises.mkdir(subDirPath, {recursive: true})
        }

        // 创建文件
        if (createFile) {
            await fs.promises.writeFile(filePath, 'This is a new file in the new subdirectory.')
            console.log(`Successfully created subdirectory and file at: ${filePath}`)
        }

    } catch (error) {
        console.error('Error creating subdirectory and file:', error)
    }
}

describe('hasFilesInDirectory Function', () => {
    beforeEach(() => {
        sinon.reset()
    })

    it('should return true when a regular file exists in the directory', async () => {
        const dirPath = '/tmp/flow-test/'
        await createSubdirectoryAndFile(dirPath, true, true)

        const result = await hasFilesInDirectory(dirPath)
        expect(result).to.be.true

        fs.rmSync(dirPath, {recursive: true})
    })

    it('should return false when no regular files exist in the directory', async () => {
        const dirPath = '/tmp/flow-test/'
        await createSubdirectoryAndFile(dirPath, false, false)

        const result = await hasFilesInDirectory(dirPath)
        expect(result).to.be.false

        fs.rmSync(dirPath, {recursive: true})
    })
})